#coding:utf8
#
# Author: CMGS
# Created on 2010-9-15
#

import time

from gevent.event import Event
from common import defcode as _defcode
from common import config as _config
from libs.rpc import rpc as _rpc
from libs.debugger import Debugger as _debugger
from libs.session import sessionPool as _sessionPool

class Editor(object):
    
    def __init__(self, fileHash, sessionId):
        self.new_info_event = Event()
        self.hash = fileHash
        self.sid = sessionId

    def getModify(self):
        modify = _sessionPool.getSessions(self.hash).get(_config.MEM_MODIFIES_NAME, None)
        session = _sessionPool.getSession(self.hash, self.sid)
        session[_config.USER_TIME_NAME] = time.time()
        if (modify is None) or (session.has_key(_config.CLIENT_PUSHED) and session[_config.CLIENT_PUSHED] >= len(modify)):
            self.new_info_event.wait()
        # 刷新数据
        modify = _sessionPool.getSessions(self.hash).get(_config.MEM_MODIFIES_NAME)
        if session.has_key(_config.CLIENT_PUSHED):
            begin = session[_config.CLIENT_PUSHED]
            session[_config.CLIENT_PUSHED] = len(modify)
        else:
            begin = 0
            session[_config.CLIENT_PUSHED] = len(modify)
        session[_config.CLIENT_READED] = True
        ret = _rpc.toJson(modify[begin: len(modify)])
        return ret

    def pushModify(self):
        self.new_info_event.set()
        self.new_info_event.clear()

def getModify(hash, sid):
    session = _sessionPool.getSession(hash, sid)
    if session is None:
        return _rpc.toJson({'code': _defcode.OPT_FAILED, 'reason': 'not login'})
    if session.has_key(_config.CLIENT_HANDLE_NAME):
        editor = session.get(_config.CLIENT_HANDLE_NAME)
    else:
        editor = Editor(hash, sid)
        session[_config.CLIENT_HANDLE_NAME] = editor
    modify = editor.getModify()
    # 切记一定要用uft-8编码
    return modify.encode('utf-8')

def pushModify(e, hash, sid):
    _debugger.out('invoke file : %s.%s' % (hash, sid))
    session = _sessionPool.getSession(hash, sid) 
    if session is not None and session.has_key(_config.CLIENT_HANDLE_NAME):
        session[_config.CLIENT_HANDLE_NAME].pushModify()
